package com.lou1052.redis.jedis.action.script;

import com.google.common.collect.Lists;
import com.lou1052.redis.jedis.api.ScriptCommands;

import java.util.List;

/**
 * 返回旧对象并设置新的对象（仅当旧值存在时才设置）
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/11/16
 * Time: 21:21
 * To change this template use File | Settings | File Templates.
 */
public class GetAndReplaceObject extends ScriptAction<Object>{
    private static final String SCRIPT="local v=redis.call('get',KEYS[1]);if v then redis.call('set',KEYS[1],ARGV[1]);end;return v;";

    private final Object newValue;

    public GetAndReplaceObject(String key ,Object newValue) {
        super(key);
        this.newValue=newValue;
    }

    @Override
    public Object callOn(ScriptCommands scriptCommands) {
        List<Object> params = Lists.newArrayList(newValue);
        return scriptCommands.eval(SCRIPT,getKey(),params);
    }
}
